How to use loc[] to select all columns, except one given column In Python Pandas

This w3wiki Dataframe is just a two dimension array with numerical index. Therefore, to except only one column we could use the columns methods to get all columns and use a not operator to exclude the columns which are not needed. This method works only when the Dataframe is not multi indexed (did not have more than one index). 

Example 1: Using Dataframe.loc[ ] with ‘!=’

Python3




df = data.loc[ : , data.columns != 'student_gender']
 
# show the dataframe
df


Output:

filtered student_gender column

Example 2: Using Dataframe.loc[ ] with isin

Python3




df= data.loc[:, ~data.columns.isin(['student_gender'])]
 
# showing the dataframe
df


Output:

filtered student_gender column

Select all columns, except one given column in a Pandas DataFrame

DataFrame Data structure are the heart of Pandas library. DataFrames are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let’s see how to Select all columns, except one given column in Pandas DataFrame in Python.

Similar Reads

Creating a DataFrame:

Python3 # import pandas library import pandas as pd   # create a Dataframe data = pd.DataFrame({     'course_name': ['Data Structures', 'Python',                     'Machine Learning'],     'student_name': ['A', 'B',                      'C'],     'student_city': ['Chennai', 'Pune',                      'Delhi'],     'student_gender': ['M', 'F',                        'M'] }) # show the Dataframe data...

Using loc[] to select all columns, except one given column

...

Using drop() Method to select all columns, except one given column

This GeeksForGeeks Dataframe is just a two dimension array with numerical index. Therefore, to except only one column we could use the columns methods to get all columns and use a not operator to exclude the columns which are not needed. This method works only when the Dataframe is not multi indexed (did not have more than one index)....

Using Series.difference() to select all columns, except one given column

...

Contact Us